package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserManageDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserManageServiceImpl implements UserManageService{

    @Autowired
    UserManageDao userManageDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<SysUser> page = userManageDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page);
    }

    @Override
    @Transactional
    public void add(SysUser user, Integer[] roleIds) {
        userManageDao.add(user);

        if(user.getId()!=null && roleIds!=null && roleIds.length>0){
            for (Integer roleId : roleIds) {
                userManageDao.set(user.getId(),roleId);
            }
        }else {
            throw new RuntimeException("添加用户角色信息发成错误!");
        }
    }

    @Override
    @Transactional
    public void edit(SysUser user, Integer[] roleIds) {
        userManageDao.edit(user);
        userManageDao.delRoles(user.getId());
        if(user.getId()!=null && roleIds!=null && roleIds.length>0){
            for (Integer roleId : roleIds) {
                userManageDao.set(user.getId(),roleId);
            }
        }else {
            throw new RuntimeException("更新用户角色信息发成错误!");
        }
    }

    @Override
    @Transactional
    public void delById(Integer userId) {
        Integer[] roleIds = userManageDao.findRoleIdByUserId(userId);
        Boolean flag = true;
        for (Integer roleId : roleIds) {
            if(roleId == 1){
                flag=false;
            }
        }
        if(!flag){
            throw new RuntimeException("超级管理员不可删除");
        }
        userManageDao.delRoles(userId);
        userManageDao.delById(userId);
    }

    @Override
    public Integer[] findRoles(Integer userId) {
        return userManageDao.findRoles(userId);
    }
}
